package com.smartboard.usbserial;

import android.content.Context;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;

import com.smartboard.usbserial.driver.UsbSerialDriver;
import com.smartboard.usbserial.driver.UsbSerialPort;
import com.smartboard.usbserial.driver.UsbSerialProber;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cheas on 2018/3/27.
 */

public class UsbSerialManager {
    private static final String TAG = "UsbSerialManager";

    private UsbManager mUsbManager;
    private List<UsbSerialPort> mEntries = new ArrayList<UsbSerialPort>();
    private DeviceUpdateListener mListener = null;

    private static Context sApplicationContext;
    private static UsbSerialManager sInst = null;

    public static void init(Context context) {
        sApplicationContext = context;
        instance();
    }

    public static UsbSerialManager instance() {
        if(sInst == null)
            sInst = new UsbSerialManager();
        return sInst;
    }

    private UsbSerialManager() {
        mUsbManager = (UsbManager) sApplicationContext.getSystemService(Context.USB_SERVICE);
    }

    public interface DeviceUpdateListener {
        void onDeviceUpdate(List<UsbSerialPort> mEntries);
    }

    public void updateDevice(DeviceUpdateListener listener) {
        mListener = listener;
        refreshDeviceList();
    }

    public List<UsbSerialPort> getPorts() {
        return mEntries;
    }

    private void refreshDeviceList() {
        new AsyncTask<Void, Void, List<UsbSerialPort>>() {
            @Override
            protected List<UsbSerialPort> doInBackground(Void... params) {
                Log.d(TAG, "Refreshing device list ...");
                SystemClock.sleep(200);

                List<UsbSerialDriver> drivers =
                        UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);

                List<UsbSerialPort> result = new ArrayList<UsbSerialPort>();
                for (UsbSerialDriver driver : drivers) {
                    List<UsbSerialPort> ports = driver.getPorts();
                    Log.d(TAG, String.format("+ %s: %s port%s",
                            driver, Integer.valueOf(ports.size()), ports.size() == 1 ? "" : "s"));
                    result.addAll(ports);
                }

                return result;
            }

            @Override
            protected void onPostExecute(List<UsbSerialPort> result) {
                mEntries.clear();
                mEntries.addAll(result);
                Log.d(TAG, "Done refreshing, " + mEntries.size() + " entries found.");
                if(mListener != null) {
                    mListener.onDeviceUpdate(mEntries);
                }
            }

        }.execute((Void) null);
    }
}
